<?php


namespace App\Http\Controllers\utils;

use ApkParser\Parser;
use App\Http\Controllers\utils\ApkParserApp;
use OSS\OssClient;

/**
 * 上传工具类
 * Class uploadUtil
 * @package App\Http\Controllers\utils
 */
class UploadUtil
{
    /**
     * 上传apk
     * @param $param
     * @param $file
     * @return false|string
     */
    public static function uploadApk($param,$file){die;
        $fileNameArr = explode('.',$file->getClientOriginalName());
        $name = 'ZYP'.time().md5_file($file);
        $suffix = $fileNameArr[count($fileNameArr)-1];
        $filePath = 'upload/apk/';
        if($suffix=='apk'){
            $fileSize = $file->getSize();
            if($fileSize>$param['size']){
                return ToolUtil::returnJson(302,'apk应用过大');
            }
            if(!file_exists($filePath)){
                mkdir($filePath,0777,true);
            }
            try {
                $data['fileSize'] = $fileSize;
                $param['remark'] = '上传apk文件';
                $parser = new Parser($file);
                $fileInfo = $parser->getManifest();
                if(!$fileInfo->getApplication()->getLabel()[0]){
                    try {
                        $data['appName'] = $parser->getResources($fileInfo->getApplication()->getLabel())[0];
                    }catch (\Exception $exception){
                        $data['appName'] = substr($file->getClientOriginalName(),0,7);
                    }
                }else{
                    $data['appName'] = $fileInfo->getApplication()->getLabel();
                }
                $data['packageName'] = $fileInfo->getPackageName();
                $data['versionName'] = $fileInfo->getVersionName();
                $data['versionCode'] = $fileInfo->getVersionCode();
                $data['fileMd5'] = md5_file($file);
                $logo = $parser->getResources($fileInfo->getApplication()->getIcon())[0];
                $icon = '/www/wwwroot/name.uiuios.com/public/upload/lost+found/apk/'.$name.'.png';
                self::getFileFromApk($file,$logo,$icon);
                $data['imgPath'] = 'http://jgy008.oss-cn-shenzhen.aliyuncs.com/apk/'.$name.'.png';
                $data['filePath'] = 'http://jgy008.oss-cn-shenzhen.aliyuncs.com/apk/'.$name.'.'.$suffix;
                move_uploaded_file($file,$filePath.$name.'.'.$suffix);
                exec('cp /www/wwwroot/homework.uiuios.com/public/'.$filePath.$name.'.'
                    .$suffix.' /www/wwwroot/name.uiuios.com/public/upload/lost+found/apk/'.$name.'.'.$suffix,$out,$int);
                if($int){
                    return ToolUtil::returnJson(300,'失败');
                }
                $param['remark'] = '上传应用';
                $param['details'] = ToolUtil::handleSuccessOrError(['packageName'=>$data['packageName'],'appName'=>$data['appName']]);
                LogUtil::addAdminLog($param);
                return ToolUtil::returnJson(200,'成功',$data);
            } catch (\Exception $e) {
                $appObj    = new ApkParserApp();
                $appObj->open($file);
                $data['appName'] = $appObj->getAppName();         // 应用名称
                $data['packageName'] = $appObj->getPackage();
                $data['versionName'] = $appObj->getVersionName();    // 版本名称
                $data['versionCode'] = $appObj->getVersionCode();    // 版本代码
                $data['fileMd5'] = md5_file($file);
                $data['imgPath'] = 'http://jgy008.oss-cn-shenzhen.aliyuncs.com/apk/'.$name.'.png';
                $data['filePath'] = 'http://jgy008.oss-cn-shenzhen.aliyuncs.com/apk/'.$name.'.'.$suffix;
                move_uploaded_file($file,$filePath.$name.'.'.$suffix);
                exec('cp /www/wwwroot/homework.uiuios.com/public/'.$filePath.$name.'.'
                    .$suffix.' /www/wwwroot/name.uiuios.com/public/upload/lost+found/apk/'.$name.'.'.$suffix,$out,$int);
                return ToolUtil::returnJson(200,'成功',$data);
            }
        }elseif($suffix=='xapk'){
            $zip = new \ZipArchive();
            $zip->open($file);
            $xApk = json_decode($zip->getFromName('manifest.json'),true);
            $data['appName'] = $xApk['name'];
            $data['packageName'] = $xApk['package_name'];
            $data['fileSize'] = $xApk['total_size'];
            $data['fileMd5'] = md5_file($file);
            $data['versionName'] = $xApk['version_name'];
            $data['versionCode'] = $xApk['version_code'];
            $data['imgPath'] = 'http://jgy008.oss-cn-shenzhen.aliyuncs.com/apk/'.$name.'.png';
            $data['filePath'] = 'http://jgy008.oss-cn-shenzhen.aliyuncs.com/apk/'.$name.'.'.$suffix;
            $param['remark'] = '上传应用';
            $param['details'] = ToolUtil::handleSuccessOrError(['packageName'=>$data['packageName'],'appName'=>$data['appName']]);
            LogUtil::addAdminLog($param);
            move_uploaded_file($file,$filePath.$name.'.'.$suffix);
            exec('cp /www/wwwroot/homework.uiuios.com/public/'.$filePath.$name.'.'
                .$suffix.' /www/wwwroot/name.uiuios.com/public/upload/lost+found/apk/'.$name.'.'.$suffix,$out,$int);
            return ToolUtil::returnJson(200,'成功',$data);
        }else{
            return ToolUtil::returnJson(301,'不是apk文件');
        }
    }

    /**
     * 上传图片
     * @param $param
     * @param $file
     * @return false|string
     */
    public static function uploadImg($param,$file){

        $fileNameArr = explode('.',$file->getClientOriginalName());
        $suffix = $fileNameArr[count($fileNameArr)-1];
        $fileSize = $file->getSize();
        if($fileSize>$param['size']){
            return ToolUtil::returnJson(301,'图片文件过大');
        }
        //获取图片的长度
        $width = getimagesize($file)[0];
        //宽度
        $height = getimagesize($file)[1];
        if($width>$param['width'] || $height>$param['height']){
            return ToolUtil::returnJson(302,'图片宽度或长度过大');
        }
        $imgArr= ['jpg','png','jpeg','gif','bmp'];
        if(!in_array($suffix,$imgArr)){
            return ToolUtil::returnJson(303,'图片格式不正确');
        }

        $save_path = 'homework/img/i'.'-'.time().'-'.mt_rand(100,999).'.'.$suffix;
        $imgPath = self::uploadAliOss($save_path,$file);

        $param['remark'] = '上传图片';
        $param['details'] = ToolUtil::handleSuccessOrError(['imgUrl'=>$imgPath]);
        LogUtil::addAdminLog($param);
        $data['imgPath'] = $imgPath;
        if($imgPath){
            return ToolUtil::returnJson(200,'成功',$data);
        }else{
            return ToolUtil::returnJson(300,'失败');
        }
        
    }


    /**
     * 上传文件
     * @param $param
     * @param $file
     * @return false|string
     */
    public static function upload_file($file,$param){

        $fileNameArr = explode('.',$file->getClientOriginalName());

        $suffix = $fileNameArr[count($fileNameArr)-1];

        $save_path = 'homework/file/f'.'-'.time().'-'.mt_rand(100,999).'.'.$suffix;
        $filePath = self::uploadAliOss($save_path,$file);

        $param['remark'] = '上传文件';
        $param['details'] = ToolUtil::handleSuccessOrError(['filePath'=>$filePath]);
        LogUtil::addAdminLog($param);
        $data['filePath'] = $filePath;
        if($filePath){
            return ToolUtil::returnJson(200,'成功',$data);
        }else{
            return ToolUtil::returnJson(300,'失败');
        }
        
    }


    /**
     * 上传pdf文件
     * @param $file
     * @return false|string
     */
    public static function uploadPdf($file){die;
        $fileNameArr = explode('.',$file->getClientOriginalName());
        $name = '';
        //截取文件.前面的部分
        for ($i=0;$i<count($fileNameArr)-1;$i++){
            $name .=$fileNameArr[$i];
        }
        $suffix = $fileNameArr[count($fileNameArr)-1];
        if(strtolower($suffix)!='pdf'){
            return ToolUtil::returnJson(301,'必须为pdf文件');
        }
        $filePath = 'upload/pdf/';
        if(!file_exists($filePath)){
            mkdir($filePath,0777,true);
        }
        move_uploaded_file($file,$filePath.$name.'.'.$suffix);
        $url = 'http://jgy008.oss-cn-shenzhen.aliyuncs.com/pdf/'.$name.'.'.$suffix;
        exec('cp /www/wwwroot/homework.uiuios.com/public/'.$filePath.$name.'.'.$suffix.' /www/wwwroot/name.uiuios.com/public/upload/lost+found/pdf/'.$name.'.'.$suffix,$out,$int);
        return ToolUtil::returnJson(200,'成功',$url);
    }

    /**
     * 从Apk包中提取指定文件,并移到$toFile
     *
     * @param $apkFile apk文件
     * @param $sourceFile apk文件中相应文件路径
     * @param $toFile 输出文件
     * @return bool
     */
    static function getFileFromApk($apkFile,$sourceFile,$toFile)
    {
        exec('unzip ' . $apkFile . ' $sourceFile -d /tmp', $out, $return);
        if (rename("/tmp/" . $sourceFile, $toFile)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 上传文件
     * @param $param
     * @return string
     */
    public static function uploadFile($param){die;
        $path = 'upload/file/';
        if(!file_exists($path)){
            mkdir($path,0755);
        }
        $fileName = $param['file']->getClientOriginalName();
        $fileNameArr = explode('.',$fileName);
        $suffix = '.'.$fileNameArr[count($fileNameArr)-1];//获取文件后缀
        $filePath = $path.time().$param['sn'].$suffix;
        if(move_uploaded_file($param['file'],$filePath)){
            return $filePath;
        }
        return "";
    }


    /**
     * 上传到oss
     * @param $object oss存储地址
     * @param $filePath 本地地址
     * @return mixed
     * @throws \OSS\Core\OssException
     */
    public static function uploadAliOss($object,$filePath){
        
        try {
            $oss = new OssClient(env('OSS_ACCESS_KEY_ID'),env('OSS_ACCESS_KEY_SECRET'),env('OSS_URL'));
            if(!$oss->doesBucketExist(env('OSS_BUCKET'))){
                $oss->createBucket(env('OSS_BUCKET'));
            }
            if($oss->doesObjectExist(env('OSS_BUCKET'),$object)){
                $oss->deleteObject(env('OSS_BUCKET'),$object);
            }
            $path = $oss->uploadFile(env('OSS_BUCKET'),$object,$filePath);
            return $path['oss-request-url'];
        }catch (\Exception $exception){
            // return $exception->getMessage();
            return false;
        }

    }


}